package com.book.iphone;

import com.book.book.domain.*;
import com.book.book.service.*;
import com.book.common.utils.R;
import com.book.iphone.domain.AppraiseDo;
import com.book.iphone.domain.QueueListItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：青松
 * 日期： 2018/1/30
 */
//图书详情
@RequestMapping("/iphone")
@Controller
public class bookInfoController {
    @Autowired
    BooksService booksService;
    @Autowired
    BookService bookService;
    @Autowired
    AppointmentService appointmentService;
    @Autowired
    UsersService usersService;
    @Autowired
    QueueService queueService;
    @Autowired
    ApplyService applyService;
    @Autowired
    BooklogService booklogService;
    @RequestMapping("/bookinfo/{bookid}")
    String getBookInfo(Model model, @PathVariable String bookid) {
        // 根据图书的id 查询图书信息
        // BookDO bookDO= bookService.getBookInfo(Integer.parseInt(bookid));
        BooksDO booksDO = booksService.get(Integer.parseInt(bookid));
        String imgs = booksDO.getBookImg();
        if (imgs != null) {
            booksDO.setBookImg(imgs.split(",")[0]);
        }
        /**
         * 根据书名去日志表中查询出用户对这本书的评价
         *回显到图书详情页
         *1、根据关键字 书名和isPass查询出 同书名的所有id
         *2、根据所有书的id，去日志表中查出用户对该书的所有评论
         *
         */
        List<AppraiseDo> booklogDOList=booklogService.getBooklogByBookName(booksDO.getBookName());
//        List<AppraiseDo> booklogDOList=booklogService.getBooklogByBookName("智能监控技术 (修订版）");
        booklogDOList=(booklogDOList.size()==0?null:booklogDOList);
        //图片的URL未做处理
        model.addAttribute("booklogDOList",booklogDOList);
        model.addAttribute("books", booksDO);
        return "book/phone/html/book_detial";
    }

    /**
     * 预约图书
     * @param bookName
     * @param request
     * @return
     */
    @GetMapping("/bookyuyue/{bookName}")
    @ResponseBody
    R bookYuYue(@PathVariable("bookName") String bookName, HttpServletRequest request) {
        String userId = null;
        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO != null) {
            userId = usersDO.getOpenId();
        } else {
            return R.error("预约失败，身份失效，请去个人中心登录");
        }
        Map<String, Object> checkmap = new HashMap<>();
        checkmap.put("bookName", bookName);
        checkmap.put("userId", userId);
        List<AppointmentDO> check = appointmentService.list(checkmap);
        Map<String, Object> queueMap=new HashMap<>();
        queueMap.put("userId",userId);
//        List<QueueDO> queueDOList = queueService.getQueueItem(userId);
        if (check.size() != 0) {   //检验用户是否已经预约过这本书了
            return R.error("已预约！");
        } else {
            if (JoinQueue(bookName, userId, request)) {
                int borrow = usersDO.getBorrowNum();
                if (borrow > 0) {
                    AppointmentDO appointmentDO = new AppointmentDO();
                    Date d = new Date();
                    appointmentDO.setUserId(userId);
                    appointmentDO.setBookName(bookName);
                    appointmentDO.setAppointTime(d);

                    int a = appointmentService.save(appointmentDO);
                    if (a == 1) {
                        usersDO.setBorrowNum(borrow - 1);//预约成功可借书量减一
                        request.getSession().setAttribute("userInfo", usersDO);//更新session中userDo数据
                        usersService.update(usersDO);
                        return R.ok("预约成功");
                    } else {
                        return R.error("预约失败！");
                    }
                } else {
                    return R.error("预约数量已达上限！");
                }
            } else {
                return R.error("预约失败，加入预约队列失败");
            }

        }

    }

    @RequestMapping("/touxiang")
    String giveTouxiang() {
        return "book/phone/html/touxiang";
    }

    /**
     * 加入队列方法
     *
     * @param bookName
     * @param userId
     * @param request
     * @return
     */
    public boolean JoinQueue(String bookName, String userId, HttpServletRequest request) {
        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO != null) {
            userId = usersDO.getOpenId();
            Map<String, Object> bookMap = new HashMap<>();
            bookMap.put("bookName", bookName);
            bookMap.put("isPass", 1);
            List<ApplyDO> applyDOS = applyService.list(bookMap);//去书库列表里查出书库里有几本书
            Map<String, Object> queueMap = new HashMap<>();//添加到预约队列里
            queueMap.put("bookName", bookName);
            List<QueueDO> queueDOList = queueService.list(queueMap);//去队列列表中拿出队列
            //applyDOS.size与queueDOList.size相等
            //贡献图书时直接将持有者放在队首，等审核通过时，放入队列列表中
            if (queueDOList.size() == 1) {
                String jsonStr = queueDOList.get(0).getQueue();
                Gson gson = new Gson();
                List<QueueListItem> queue = gson.fromJson(jsonStr, new TypeToken<List<QueueListItem>>() {
                }.getType());
                QueueListItem item = new QueueListItem();
                item.setSeq(queue.size() + 1);
                item.setAddress(usersDO.getAddress());
                item.setNickName(usersDO.getNickName());
                item.setPhone(usersDO.getPhone());
                item.setUserId(userId);
                queue.add(item);
                queueDOList.get(0).setQueue(new Gson().toJson(queue));
                int a = queueService.update(queueDOList.get(0));
                return a == 1 ? true : false;
            } else {
                int index = 0;
                int length = queueDOList.get(0).getQueue().split("}").length;
                for (int i = 1; i <= queueDOList.size() - 1; i++) {
                    if (queueDOList.get(i).getQueue().split("}").length == 1) {
                        index = i;
                        length = 1;
                        break;
                    } else {
                        if (length > queueDOList.get(i).getQueue().split("}").length) {
                            length = queueDOList.get(i).getQueue().split("}").length;
                            index = i;
                        }
                    }
                }//拿到最短队列
                String jsonStr = queueDOList.get(index).getQueue();
                Gson gson = new Gson();
                List<QueueListItem> queue = gson.fromJson(jsonStr, new TypeToken<List<QueueListItem>>() {
                }.getType());
                QueueListItem item = new QueueListItem();
                item.setSeq(queue.size() + 1);
                item.setAddress(usersDO.getAddress());
                item.setNickName(usersDO.getNickName());
                item.setPhone(usersDO.getPhone());
                item.setUserId(userId);
                queue.add(item);
                queueDOList.get(index).setQueue(new Gson().toJson(queue));
                int a = queueService.update(queueDOList.get(index));
                return a == 1 ? true : false;
            }
        } else {
            return false;
        }
    }
    /**
     *
     *根据书名查询出所有的评论
     * @param bookName
     * @return
     */
    @RequestMapping("/bookComment/{bookName}")
    String bookComment(@PathVariable("bookName") String bookName,Model model){
        List<AppraiseDo> booklogDOList=booklogService.getBooklogByBookName(bookName);
//        List<AppraiseDo> booklogDOList=booklogService.getBooklogByBookNameNoLimit("智能监控技术 (修订版）");
        booklogDOList=(booklogDOList.size()==0?null:booklogDOList);
        //图片的URL未做处理
        model.addAttribute("booklogDOList",booklogDOList);
        model.addAttribute("bookName",bookName);
        return "book/phone/html/book_comment";
    }
}